package cn.tedu.boke.portal.service.impl;

import cn.tedu.boke.portal.exception.ServiceException;
import cn.tedu.boke.portal.mapper.UserRoleMapper;
import cn.tedu.boke.portal.model.User;
import cn.tedu.boke.portal.mapper.UserMapper;
import cn.tedu.boke.portal.model.UserRole;
import cn.tedu.boke.portal.service.IUserService;
import cn.tedu.boke.portal.vo.RegisterVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author tedu.cn
 * @since 2021-11-01
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService
{
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;


    @Override
    public void register(RegisterVo registerVo)
    {
        User user = userMapper.findUserByUsername(registerVo.getUsername());

        if (user != null)
        {
            throw new ServiceException("用户已被注册");
        }

        //密码加密
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd = "{bcrypt}" + encoder.encode(registerVo.getPassword());
        //实例化用户对象 ,并赋值
        User u = new User()
                .setUsername(registerVo.getUsername())
                .setNickname(registerVo.getNickname())
                .setPassword(pwd)
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0)
                .setType(1);

        ///新增用户
        int num = userMapper.insert(u);
        if (num != 1)
        {
            throw new ServiceException("数据库忙");
        }
        System.out.println("新增用户:" + u);
        System.out.println("新增用户Id:" + u.getId());
        //执行新增用户角色表操作
        UserRole userRole = new UserRole()
                .setUserId(u.getId())
                .setRoleId(2);
        System.out.println("新增用户权限:" + userRole);
        num = userRoleMapper.insert(userRole);
        if (num != 1)
        {
            throw new ServiceException("数据库忙");
        }
    }

    @Override
    public User findUserByUsername(String userName)
    {
        User user = userMapper.findUserByUsername(userName);
        return user;
    }

    @Override
    public int cleanUserById(Integer userId)
    {
        return userMapper.cleanUserById(userId);
    }

    @Override
    public int lockUserById(Integer userId)
    {
        return userMapper.lockUserById(userId);
    }

    @Override
    public int unLockUserById(Integer userId)
    {
        return userMapper.unLockUserById(userId);
    }


}
